package com.foreknow.service.impl;

import com.foreknow.dao.CartDao;
import com.foreknow.dao.impl.CartDaoImpl;
import com.foreknow.po.Cart;
import com.foreknow.service.CartService;
import com.foreknow.util.DBUtil;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class CartServiceImpl implements CartService {
    @Override
    public List<Cart> listCart(Cart cart) {
        List<Cart> list = new ArrayList<>();
        CartDao cartDao = new CartDaoImpl();
        try {
            list = cartDao.listCart(cart);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close();
        }
        return list;
    }

    @Override
    public Integer saveCart(String userId, Integer businessId, Integer foodId) {
        CartDao cartDao = new CartDaoImpl();
        Integer result = 0;
        try {
            DBUtil.beginTransaction();//开启一个事务
            result =cartDao.saveCart(userId,businessId,foodId);
            DBUtil.commitTransaction();//提交一个事务

        } catch (Exception e) {
            try {
                DBUtil.rollbackTransaction();  //回滚一个事务
            } catch (Exception e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        } finally {
            DBUtil.close(); // 关闭Connection
        }
        return result;
    }

    @Override
    public Integer updateCart(String userId, Integer businessId, Integer foodId, Integer quantity) {
        CartDao cartDao = new CartDaoImpl();
        Integer result = 0;
        try {
            DBUtil.beginTransaction();//开启一个事务
            result =cartDao.updateCart(userId,businessId,foodId,quantity);
            DBUtil.commitTransaction();//提交一个事务

        } catch (Exception e) {
            try {
                DBUtil.rollbackTransaction();  //回滚一个事务
            } catch (Exception e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        } finally {
            DBUtil.close(); // 关闭Connection
        }
        return result;
    }

    @Override
    public Integer removeCart(Cart cart) {
        CartDao cartDao = new CartDaoImpl();
        Integer result = 0;
        try {
            DBUtil.beginTransaction();//开启一个事务
            result =cartDao.removeCart(cart);
            DBUtil.commitTransaction();//提交一个事务

        } catch (Exception e) {
            try {
                DBUtil.rollbackTransaction();  //回滚一个事务
            } catch (Exception e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        } finally {
            DBUtil.close(); // 关闭Connection
        }
        return result;
    }
}
